<?php

namespace App\Jobs;

use App\Http\Util\Wechat;

use App\Model\House;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class WarningMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $data;
    public $tries = 1;
    public $timeout = 12;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
        //因为要导入大文件 需要很久时间
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try{
            $data = $this->data;
            $house = House::query()->where('id',$data['house_id'])->first();
            if($house){
                $houseName = $house->estate_name.$house->name;
            }else{
                $houseName = '未知房源';
            }
            $token = Wechat::getAccessToken();
            $postData = [
                'touser' => $data['openid'],
                'template_id' => 'veACA0Y1QHf-YBqZzJVEYIA5E4cnjd2o7wj1V8JxebQ',
                'data' => [
                    'thing8' => ['value' =>  $houseName],
                    'thing9' => ['value' => '电表'],
                    'thing10' => ['value' => $data['du'].'度'],
                    'time41' => ['value' =>date('Y年m月d日')],
                    'thing4' => ['value' => '您的剩余电量已不足请及时处理']
                ]
            ];
            $postData =json_encode($postData);
            $result =  Wechat::sendMessage($postData,$token);
            $result  = json_decode($result,true);
            if($result['errcode'] == '40001'){
                Redis::del('WECHAT_TOKEN');
                $token = Wechat::getAccessToken();
                $postData = [
                    'touser' => $data['openid'],
                    'template_id' => 'veACA0Y1QHf-YBqZzJVEYIA5E4cnjd2o7wj1V8JxebQ',
                    'data' => [
                        'thing8' => ['value' =>  $houseName],
                        'thing9' => ['value' => '电表'],
                        'thing10' => ['value' => $data['du'].'度'],
                        'time41' => ['value' =>date('Y年m月d日')],
                        'thing4' => ['value' => '您的剩余电量已不足请及时处理']
                    ]
                ];
                $postData =json_encode($postData);
                $result =  Wechat::sendMessage($postData,$token);
                $result  = json_decode($result,true);
            }
            Log::info('告警回复：'.json_encode($result));
        }catch (\Exception $e){
            Log::info($e->getMessage());
        }
    }
}

